<?php

namespace App\Console\Commands;

use App\Http\Biz\ShopBiz;
use App\Http\Biz\SuppManagerBiz;
use App\Http\Biz\SuppOrderBiz;
use App\Http\Biz\SuppReportBiz;
use App\Http\Model\PtDayTotalProfits;
use App\Http\Model\PtGoods;
use App\Http\Model\PtGoodsOrderMid;
use App\Http\Model\PtGoodsSpec;
use App\Http\Model\PtPreSale;
use App\Http\Model\Shop;
use App\Http\Model\ShopAccount;
use App\Http\Model\ShopAccountRoleMid;
use App\Http\Model\ShopDayStat;
use App\Http\Model\ShopDayTotalProfits;
use App\Http\Model\ShopGoodsInoutMid;
use App\Http\Model\ShopModule;
use App\Http\Model\ShopRoleModuleMid;
use App\Http\Model\ShopTorageInOut;
use App\Http\Model\Supp;
use App\Http\Model\SuppDayStat;
use App\Http\Model\SuppPurchase;
use App\Http\Model\SuppPurchaseMid;
use App\Http\Model\UserPtDict;
use App\Http\Utils\Common\Consts;
use App\Http\Utils\Common\WechatUtils;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Log;

class You extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'conn:init';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $complate_id = Consts::TEMPLATE_ID;
        $own_id = 18;
        $account_type = 1;
        $openids = ['obZDz0JlXXI_KmtiNneXp41dq54g'];//132账号门店的openid
        $params = [
            'keyword1'=> [
                "value"=>"舟山渔场",
                "color"=>"#173177"
            ],
            'keyword2'=> [
                "value"=>Carbon::now(),
                "color"=>"#173177"
            ],
            'keyword3'=> [
                "value"=>"货物已经出库，请及时签收",
                "color"=>"#173177"
            ]
        ];
        $page = 'pages/shop/shop_storage/shop_storage?id=16';
        $util = new WechatUtils();
        $util->sendTemplate($complate_id, $own_id, $account_type, $openids,$params,$page);
//        $tmpBiz = new SuppOrderBiz();
//        $data = $tmpBiz->mainDataBiz(18,16);
//        $data = $tmpBiz->sendOrderGoodsBiz(17,2,16);
//        $data = $tmpBiz->readPickupByDayBiz(17,2017,11,24);
//        $tmpBiz = new SuppManagerBiz();
//        $tmpBiz->addmanagerBiz(19,17,'13188888888',17);
//        $tmpBiz->deleteAccountRoleBiz(19,15,29);
//        $data = $tmpBiz->getAccountDetailByIdBiz(18,16);
//        $data = $tmpBiz->managerListBiz(18,16);
//        Log::info($data);
//        PtGoodsSpec::updateOrCreate(['id'=>80],['price'=>0.01]);
//        $order_num = '5a13fe4c55d15';
//        Log::info($this->getDataList(2017,11,22));
//        $data = SuppDayStat::query()->groupBy('year')->groupBy('month')->groupBy('day')->paginate(Consts::PAGE_SIZE);
//        foreach ($data->items() as $item){
//
//        }
//        return;
//        $yesterday = Carbon::yesterday();
//        //列出每个供应商所得的分润
//        $supp_lists = SuppDayStat::where('supp_day_stat.date',$yesterday)
//            ->leftJoin('supp','supp.id','=','supp_day_stat.supp_id')->groupBy('supp_day_stat.supp_id')
//            ->get([DB::raw('sum(supp_day_stat.total_profits) as total_profits'),'supp.id','supp.name','supp.phone']);
//        Log::info($supp_lists);
//        //列出每个提货点所得分润
//        $pickup_lists = ShopDayTotalProfits::where([
//                'year'=>$yesterday->year,
//                'month'=>$yesterday->month,
//                'day'=>$yesterday->day
//            ])->leftJoin('shop','shop.id','=','shop_day_total_profits.pickup_id')
//                ->groupBy('shop_day_total_profits.pickup_id')
//            ->get([DB::raw('sum(shop_day_total_profits.total_profits) as total_profits'),'shop.id','shop.shop_name as name','shop.phone']);
//        Log::info($pickup_lists);
    }

    public function getDataByDay()
    {
        $data = SuppDayStat::query()
            ->select('year','month','day','date')
            ->orderBy('date','desc')
            ->groupBy('year')
            ->groupBy('month')
            ->groupBy('day')
            ->paginate(Consts::PAGE_SIZE);
        foreach ($data->items() as $item){
            //前一天订单总金额（单元：元）
            $total_money = PtGoodsOrderMid::where([
                    'year'=>$item->year,
                    'month'=>$item->month,
                    'day'=>$item->day
                ])->where('status','>=',2)->sum('price') / 100;
            //前一天给供应商的金额（分润）
            $supp_total_profits = SuppDayStat::where([
                    'year'=>$item->year,
                    'month'=>$item->month,
                    'day'=>$item->day
                ])->sum('total_profits') / 100;
            //前一天给提货点的金额（分润）
            $pickup_total_profits = ShopDayTotalProfits::where([
                    'year'=>$item->year,
                    'month'=>$item->month,
                    'day'=>$item->day
                ])->sum('total_profits') / 100;
            //前一天平台所得分润
            $pt_total_profits = PtDayTotalProfits::where([
                    'year'=>$item->year,
                    'month'=>$item->month,
                    'day'=>$item->day
                ])->sum('total_profits') / 100;
            $item->total_money = $total_money;
            $item->supp_total_profits = $supp_total_profits;
            $item->pickup_total_profits = $pickup_total_profits;
            $item->pt_total_profits = $pt_total_profits;
        }
        return $data;
    }

    public function getDataList($year,$month,$day,$flag = 0)
    {
        if($flag == 0){//供应商所得的分润
            $lists = SuppDayStat::query()
                ->where(['supp_day_stat.year'=>$year,'supp_day_stat.month'=>$month, 'supp_day_stat.day'=>$day])
                ->leftJoin('supp','supp.id','=','supp_day_stat.supp_id')->groupBy('supp_day_stat.supp_id')
                ->get(['supp.bank_account','supp.bank_user',DB::raw('sum(supp_day_stat.total_profits) as total_profits'),'supp.id','supp.name','supp.phone']);
        }else{//门店所得的分润
            $lists = ShopDayTotalProfits::query()
                ->where(['shop_day_total_profits.year'=>$year,'shop_day_total_profits.month'=>$month, 'shop_day_total_profits.day'=>$day])
                ->leftJoin('shop','shop.id','=','shop_day_total_profits.pickup_id')
                ->groupBy('shop_day_total_profits.pickup_id')
                ->get(['shop.bank_account','shop.bank_user',DB::raw('sum(shop_day_total_profits.total_profits) as total_profits'),'shop.id','shop.shop_name as name','shop.phone']);
        }
        return $lists;
    }

    public function calPurchase($order_num)
    {
        try {
            DB::beginTransaction();
            //获取订单数据
            $order_mid = PtGoodsOrderMid::query()
                ->where(['order_num' => $order_num, 'status' => 2, 'account_types' => 1])
                ->get();//已支付
            $total_num = 0;
            foreach ($order_mid as $item) {
                $total_num += $item->num;
                $purchase = SuppPurchase::firstOrCreate([
                    'year' => $item->year,
                    'month' => $item->month,
                    'day' => $item->day,
                    'supp_id' => $item->supp_id,
                    'serial_num' => $item->serial_num
                ]);
                //自增订单总金额
                $purchase->increment('total_money', $item->price * 100);
                //自增订单总数
                $purchase->increment('total_num', 1);
                //修改采购总表数据
                $mid = SuppPurchaseMid::firstOrCreate([
                    'purchase_id' => $purchase->id,
                    'goods_id' => $item->goods_id,
                    'goods_name' => $item->goods_name,
                    'spec_id' => $item->spec_id,
                    'spec_name' => $item->spec_name,
                    'sale_unit_name' => $item->sale_unit_name,
                ]);
                //自增采购数量
                $mid->increment('num', $item->sale_unit_val * $item->num);
                $shop = Shop::find($item->pickup_id);
                //修改出库表数据
                $torage_in_out = ShopTorageInOut::firstOrCreate([
                    'serial_num' => $item->serial_num,
                    'pickup_id' => $item->pickup_id,
                    'supp_id' => $item->supp_id,
                ]);
                if($shop != null){
                    $torage_in_out->pickup_name = $shop->shop_name;
                    $torage_in_out->pickup_phone = $shop->phone;
                    $torage_in_out->pickup_addr = $shop->pro.$shop->city.$shop->area.$shop->addr;
                    $torage_in_out->save();
                }
                //更新出库表商品数据
                $inout_mid = ShopGoodsInoutMid::firstOrCreate([
                    'inout_id' => $torage_in_out->id,
                    'goods_id' => $item->goods_id,
                    'spec_id' => $item->spec_id,
                    'serial_num' => $item->serial_num
                ]);
                $inout_mid->goods_name = $item->goods_name;
                $inout_mid->spec_name = $item->spec_name;
                $inout_mid->save();
                //自增商品数量
                $inout_mid->increment('num',$item->num);
            }
            //统计总的商品数量
            if($total_num > 0 && $torage_in_out != null){
                $torage_in_out->increment('num',$total_num);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
        }
    }
}
